package pac

import (
	"fmt"
	"runtime"
	"strconv"
	"time"

	"slgw_web/serial/dto"
	"slgw_web/serial/util"

	models "openzbox.com/frame/echo/models/sl_gw01"
)

type Timer struct {
	ID     string
	Ticker *time.Ticker
	Done   chan bool
}

var timers map[string]*Timer

func init() {
	fmt.Println("定时任务初始化")
	InitTimers()
}

func InitTimers() {
	timers = make(map[string]*Timer)
}

//var triggerChan = make(chan bool, 1)

// var triggerChan0 = make(chan bool, 1)
func printStackTrace() {
	// 使用 runtime.Stack 获取堆栈信息
	buf := make([]byte, 2048)
	runtime.Stack(buf, false)
	util.Error("错误堆栈信息:", string(buf))
}

// 开启一个定时任务
/* timerType 0:心跳任务 1：采集任务 2:上报任务 3:读取tcp返回值 4:dtu的心跳任务 5:采集推送数据 6:网关时间 7:添加采集缓存到数据库
8:mqtts定时发布 9:modbusTcp 10:集中器心跳包 11:集中器上报 12:定时自动校时
*/
func CreateTimer(id string, interval time.Duration, inputInfo string, timerType int, sb models.DeviceInfo, t *dto.CollectSet, concentratorHeartbeat *[][]byte) {
	ticker := time.NewTicker(interval)
	done := make(chan bool)
	timers[id] = &Timer{
		ID:     id,
		Ticker: ticker,
		Done:   done,
	}
	var tCopy dto.CollectSet
	if t != nil {
		tCopy = *t
	}
	go func() {
		//fmt.Println("定时")
		defer func() {
			// 关闭通道，通知所有等待的 Goroutines 退出
			fmt.Println("关闭通道")
			close(done)
			if err := recover(); err != nil {
				if err2, ok := err.(error); ok {
					util.Error("timerType:" + strconv.Itoa(timerType) + ",id:" + id + ",定时任务错误:" + err2.Error())
				} else {
					util.Error("timerType:"+strconv.Itoa(timerType)+",id:"+id+",定时任务错误:", err)
				}
				printStackTrace()
				//util.Error(err)
				StopTimer(id)
				CreateTimer(id, interval, inputInfo, timerType, sb, t, concentratorHeartbeat)
				//if timerType == 2 {
				//triggerChan <- true
				//} //else if timerType == 0 {
				//triggerChan0 <- true
				//}
			}
		}()
		for {
			select {
			case <-ticker.C:
				//fmt.Println("id", id, interval, inputInfo, timerType, tCopy)
				if timerType == 0 {
					//<-triggerChan0
					SendData(inputInfo, sb)
					// 通知下一个可以开始了
					//triggerChan0 <- true
				} else if timerType == 1 {
					TaskCollectData(tCopy)
				} else if timerType == 2 {
					// 等待上一个 TaskReportedData 完成
					//<-triggerChan
					TaskReportedData(sb, 1)
					// 通知下一个可以开始了
					//triggerChan <- true
				} else if timerType == 3 {
					ReadConn(sb)
				} else if timerType == 4 {
					bytes := []byte(inputInfo)
					SendDataByte(bytes, sb)
				} else if timerType == 5 {
					CollectWebsocket()
				} else if timerType == 6 {
					GetTime()
				} else if timerType == 7 {
					AddCollectDataList()
				} else if timerType == 8 {
					TaskReportedMqttData(sb, 1)
				} else if timerType == 9 {
					WriteModbusTCPData(sb)
				} else if timerType == 10 {
					for _, c := range *concentratorHeartbeat {
						SendDataByte(c, sb)
					}

				} else if timerType == 11 {
					TaskReportedConcentratorData(sb)
				} else if timerType == 12 {
					TaskSetTime()
				}

				//fmt.Println("Task", id, "is triggered.")
			case <-done:
				fmt.Println("Task", id, "is stopped.")
				return
			}
		}
	}()
}

func StopTimer(id string) {
	timer, ok := timers[id]
	if !ok {
		fmt.Println("Task", id, "not found.")
		return
	}

	timer.Ticker.Stop()
	//timer.Done <- true
	delete(timers, id)
	fmt.Println("Task", id, "is stopped.")
}

// func main() {
// 	InitTimers()

// 	// 创建定时任务
// 	CreateTimer("Task1", 2*time.Second)
// 	CreateTimer("Task2", 3*time.Second)
// 	CreateTimer("Task3", 5*time.Second)

// 	// 等待一段时间后停止指定的定时任务
// 	time.Sleep(10 * time.Second)
// 	StopTimer("Task1")
// 	StopTimer("Task3")

// 	// 等待一段时间后停止剩余的定时任务
// 	time.Sleep(5 * time.Second)
// 	for id := range timers {
// 		StopTimer(id)
// 	}
// }
